# -*- coding: utf-8 -*-
# @Time    : 2022/4/12 16:48
# @Author  : zyw
# @Email   : panda_kings@163.com
# @File    : news.py
from flask import Blueprint,g,jsonify,request
from flask_restful import Api,Resource,reqparse

from common.models import db
# from common.models.channeles import Channels
# from common.models.news import NewsInfo

# 创建蓝图
news_bp = Blueprint('news',__name__, url_prefix='/news')

api = Api(news_bp)


class NewsResource(Resource):
    def post(self):
        """用户发布文章"""
        # 1. 获取用户id, 频道id, 文章的标题, 文章内容
        parse = reqparse.RequestParser()
        parse.add_argument('uid',location='form')
        parse.add_argument('cid',location='form')
        parse.add_argument('title',location='form')
        parse.add_argument('content',location='form')
        parse.add_argument('cover',location='form')
        args = parse.parse_args()
        user_id = args.get('uid')
        channel_id = args.get('cid')
        title = args.get('title')
        content = args.get('content')
        cover = args.get('cover')
        print(channel_id,user_id,cover,content,title)
        # 校验参数
        if not all([user_id, channel_id, title, content,cover]):
            return jsonify({'msg':"请完善数据","code":401})
        # 校验频道
        channel = Channels.query.filter_by(cid=channel_id).first()
        if not channel:
            return jsonify({'msg':"此频道不存在,请先添加频道","code":400})
        if not cover:
            return jsonify({'msg': "请填写封面", "code": 400})
        else:
            # 频道存在
            new = NewsInfo(nid=channel_id, user_id=user_id, title=title, content=content,cover=cover)
            db.session.add(new)
            db.session.commit()
            return jsonify({'msg':'发布文章成功',"data":{'article_id':new.nid,"title":new.title}})

    def get(self):
        """查询频道下的文章"""
        # 获取频道id, 频道传来的时候可以是列表
        # 获得时候频道也得list
        # 根据频道获取频道下的文章
        # 拼接数据,返回
        """
        {
            "msg":"ok",
            "data":[
                {
                    'nid':1,
                    "user_id":1,
                    "user":zhangsan,
                    "title":"母猪的产后护理"
                    .....
                },
                ....
            ]
        }
        """
        parse = reqparse.RequestParser()
        parse.add_argument('cid', type=str, location='json')  # cid 可以传来多个频道id [1,2,3,4]
        args = parse.parse_args()
        cid_list = eval(args.get('cid'))
        news_list = []
        for id in cid_list:
            # id 是频道id,根据频道id 获取频道信息
            channel = Channels.query.filter_by(cid=id).first()
            # 根据channel 获取频道文章
            news = channel.newsinfo.all()
            for new in news:
                news_list.append({
                    'nid':new.nid,
                    'title':new.title,
                    'comment_count': new.comment_count,
                    'good_count': new.good_count
                })

        return jsonify({'msg':"获取频道文章成功","code":200})

    def patch(self):
        """修改时可以修改某一些字段,局部修改"""
        # 1. 获取前端传来的数据
        parse = reqparse.RequestParser()
        parse.add_argument('nid', location='args')
        parse.add_argument('title', location='form')
        parse.add_argument('content', location='form')
        args = parse.parse_args()
        new_id = args.get('nid')
        title = args.get('title')
        content = args.get('content')
        print(">>>>>",new_id,  content, title)
        # 校验参数
        if not all([new_id,  title, content]):
            return jsonify({'msg': "请完善数据", "code": 401})
        new = NewsInfo.query.filter_by(nid=new_id)
        if not new:
            #没有此文章
            return jsonify({'msg':"没有此文章","code":400})
        else:
            new.update({'title':title, "content":content})
            db.session.commit()
            return jsonify({'msg':'修改成功','code':200, 'data':{'article':new_id, 'content':content}})


class UserNew(Resource):
    def get(self):
        """获取用户写的文章"""
        parse = reqparse.RequestParser()
        parse.add_argument('uid', location='args')
        args = parse.parse_args()
        user_id =args.get('uid')
        news = NewsInfo.query.filter_by(user_id=user_id).all()
        if not news:
            return jsonify({'msg':"用户还没发表文章","code":400})
        else:
            news_list = []
            for new in news:
                news_list.append({
                    'art_id':new.nid,
                    "art_title":new.title,
                    'art_content':new.content,
                    'art_comment_num': new.comment_count
                })
            """
            {
                "msg":'xxx',
                "data":[
                    {"art_id":1,'art_title':1243}
                ]
            }
            """
            return jsonify({'msg':'获取成功',"data":news_list})

    def delete(self):
        """删除指定的文章"""
        parse = reqparse.RequestParser()
        parse.add_argument('nid', location='args')
        parse.add_argument('uid', location='args')
        args = parse.parse_args()
        new_id = args.get('nid')
        user_id = args.get('uid')
        new = NewsInfo.query.filter_by(nid=new_id, user_id=user_id).first()
        if new:
            # 此时不是从数据库中删除, 是把删除的状态改成True
            new.update({'is_delete':True})
            db.session.commit()
            return jsonify({'msg':"删除成功","code":204})
        else:
            return jsonify({'msg':"没有这个文章,请核对","code":400})



class NewsInfoRes(Resource):
    def get(self):
        """获取文章详情"""
        # 1. 获取文章id
        # 2. 从文章表中获取数据
        # 3. 返回
        """
        {
            "msg":'ok',
            "data":{
                "nid":1,
                "title":"Numpy 处理时间序列",
                .....
            }
        }
        """
        parse = reqparse.RequestParser()
        parse.add_argument('nid')
        args = parse.parse_args()
        nid = args.get('nid')
        try:
            news = NewsInfo.query.filter_by(nid=nid).first()
            data_ = {
                'nid': news.nid,
                "title": news.title
            }
            return jsonify({"msg": "获取文章详情成功", "code": 200, "data": data_})
        except Exception as e:
            print("获取文章详情失败",e)
            return jsonify({'msg':"失败"})


api.add_resource(NewsResource,'/news')
api.add_resource(NewsInfoRes,'/newsinfo')